<script setup lang="ts">
const emits = defineEmits(["handleQuery"]);
const dialog = reactive({
  visible: false,
  title: "",
  width: "60%",
  type: "",
});
import { SourceItem } from "@/api/dict/source/types";
import { getSourceTree } from "@/api/dict/source";

import { RegionVo } from "@/api/system/region/types";
import { getOpenZone } from "@/api/system/region";

const ruleFormRef = ref(ElForm);
import { CreateForm } from "@/api/customer/allocate/types";
import { createCustomer } from "@/api/customer/allocate";
const formData = reactive<CreateForm>({
  fullname: "",
  sex: 0,
  mobile: "",
  wechat: "",
  telephone: "",
  source_id: 0,
  zone_id: 0,
  zone: [],
  event_date: "",
  table_amount: "",
  budget: "",
  remark: "",
});

const sourceOptions = ref<SourceItem[]>([]);
const initSourceTree = async () => {
  const { data } = await getSourceTree();
  sourceOptions.value = [{ id: 0, title: "请选择渠道", children: data }];
};

// 初始化区域
const zoneOptions = ref<RegionVo[]>([]);
const initZone = async () => {
  const { data } = await getOpenZone(802);
  data.unshift({ id: 0, shortname: "请选择区域" });
  zoneOptions.value = data;
};

const addZone = (value: number) => {
  if (value === 0) return;
  if (formData.zone.length >= 3) {
    ElMessage.error("最多只能选择3个区域");
    formData.zone_id = 0;
    return;
  }

  // 如果已经选择了该区域，则不再添加
  if (formData.zone.find((i) => i.id === value)) {
    formData.zone_id = 0;
    return;
  }

  const item = zoneOptions.value.find((i) => i.id === value);
  if (item) formData.zone.push(item);
  formData.zone_id = 0;
};

const removeZone = (item: RegionVo) => {
  const index = formData.zone.findIndex((i) => i.id === item.id);
  formData.zone.splice(index, 1);
};

const rules = reactive({
  // 不为空时, 验证手机号格式
  mobile: [
    {
      validator: (rule: any, value: string, callback: any) => {
        if (value) {
          const reg = /^1[3456789]\d{9}$/;
          if (!reg.test(value)) {
            callback(new Error("手机号格式不正确"));
          } else {
            callback();
          }
        } else {
          callback();
        }
      },
      trigger: "blur",
    },
  ],
  // 不为空时, 验证座机格式
  telephone: [
    {
      validator: (rule: any, value: string, callback: any) => {
        if (value) {
          const reg = /^([0-9]{3,4}-)?[0-9]{7,8}$/;
          if (!reg.test(value)) {
            callback(new Error("座机格式不正确"));
          } else {
            callback();
          }
        } else {
          callback();
        }
      },
      trigger: "blur",
    },
  ],
  // 验证source_id > 0
  source_id: [
    { required: true, message: "渠道不能为空", trigger: "blur" },
    {
      validator: (rule: any, value: number, callback: any) => {
        if (value === 0) {
          callback(new Error("请选择渠道"));
        } else {
          callback();
        }
      },
      trigger: "change",
    },
  ],
  zone_id: [{ required: true, message: "区域不能为空", trigger: "blur" }],
  zone: [{ required: true, message: "区域不能为空", trigger: "blur" }],
  remark: [{ required: true, message: "备注不能为空", trigger: "blur" }],
});

const closeDialog = () => {
  dialog.visible = false;
  dialog.title = "";
};

const showDialog = () => {
  dialog.visible = true;
  dialog.title = "添加客资";
  initSourceTree();
  initZone();
};

const doSubmit = () => {
  // mobile、wechat、telephone都为空提示
  if (!formData.mobile && !formData.wechat && !formData.telephone) {
    ElMessage.error("手机号、微信号、座机必须任选其一");
    return;
  }

  // 如果手机号不为空，验证手机号格式
  if (formData.mobile) {
    const reg = /^1[3456789]\d{9}$/;
    if (!reg.test(formData.mobile)) {
      ElMessage.error("手机号格式不正确");
      return;
    }
  }

  // 如果座机不为空，验证座机格式
  if (formData.telephone) {
    const reg = /^([0-9]{3,4}-)?[0-9]{7,8}$/;
    if (!reg.test(formData.telephone)) {
      ElMessage.error("座机格式不正确");
      return;
    }
  }

  // 如果区域没有选择，提示选择区域
  if (formData.zone.length === 0) {
    ElMessage.error("请选择区域");
    return;
  }

  ruleFormRef.value.validate((valid: boolean) => {
    if (valid) {
      createCustomer(formData).then((response) => {
        const { code, msg } = response.data;
        if (code !== 200) {
          ElMessage.success(msg);
          closeDialog();
          emits("handleQuery");
        } else {
          ElMessage.error(msg);
        }
      });
    } else {
      return false;
    }
  });
};

defineExpose({
  showDialog,
});
</script>

<template>
  <el-dialog
    class="form-dialog"
    v-model="dialog.visible"
    :title="dialog.title"
    :width="dialog.width"
    append-to-body
    @close="closeDialog"
    center
  >
    <!-- 用户新增/编辑表单 -->
    <el-form
      ref="ruleFormRef"
      :model="formData"
      :rules="rules"
      label-width="5rem"
    >
      <el-card class="form-card">
        <template #header>
          <div class="card-header">
            <span>基本信息</span>
          </div>
        </template>
        <el-row>
          <el-col :span="8">
            <el-form-item label="客户姓名" prop="fullname">
              <el-input v-model="formData.fullname" clearable></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="手机号" prop="mobile">
              <el-input v-model="formData.mobile" clearable></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="性别" prop="sex">
              <el-radio-group v-model="formData.sex">
                <el-radio :label="1">男</el-radio>
                <el-radio :label="0">女</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="渠道" prop="source_id">
              <el-tree-select
                class="w-full"
                v-model="formData.source_id"
                placeholder="请选择渠道"
                :data="sourceOptions"
                filterable
                check-strictly
                value-key="id"
                :props="{
                  label: 'title',
                  children: 'children',
                  isLeaf: 'isLeaf',
                }"
                :render-after-expand="false"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="微信号" prop="wechat">
              <el-input v-model="formData.wechat" clearable></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="座机" prop="telephone">
              <el-input v-model="formData.telephone" clearable></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-alert title="手机号、微信号、座机必须任选其一" type="error" />
          </el-col>
        </el-row>
      </el-card>

      <el-card class="form-card margin-top-10">
        <template #header>
          <div class="card-header">
            <span>婚宴/婚庆信息</span>
          </div>
        </template>
        <el-row v-if="formData.zone.length > 0">
          <el-col :span="24">
            <el-form-item label="已选区域">
              <el-tag
                class="margin-right-10"
                v-for="item in formData.zone"
                :key="item.id"
                closable
                @close="removeZone(item)"
                >{{ item.shortname }}</el-tag
              >
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="6">
            <el-form-item label="区域" prop="zone_id">
              <el-select
                v-model="formData.zone_id"
                placeholder="请选择区域"
                clearable
                filterable
                @change="addZone"
              >
                <el-option
                  v-for="item in zoneOptions"
                  :key="item.id"
                  :label="item.shortname"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="婚期" prop="event_date">
              <el-input v-model="formData.event_date" clearable></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="桌数" prop="source">
              <el-input v-model="formData.table_amount" clearable></el-input>
            </el-form-item>
          </el-col>

          <el-col :span="6">
            <el-form-item label="预算" prop="budget">
              <el-input v-model="formData.budget" clearable></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-card>

      <el-card class="form-card margin-top-10">
        <template #header>
          <div class="card-header">
            <span>备注信息</span>
          </div>
        </template>
        <el-row>
          <el-col :span="24">
            <el-form-item label="备注" prop="remark">
              <el-input
                type="textarea"
                v-model="formData.remark"
                clearable
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-card>
    </el-form>

    <template #footer>
      <span class="dialog-footer">
        <el-button @click="closeDialog">关闭</el-button>
        <el-button type="primary" @click="doSubmit">提交</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<style lang="scss" scoped>
.margin-top-10 {
  margin-top: 10px;
}

.margin-right-10 {
  margin-right: 10px;
}

.w-full {
  width: 100%;
}
</style>
